package cn.mujiankeji.mbrowser.界面.小窗页.请求

import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import cn.mujiankeji.mbrowser.app.应用接口
import cn.mujiankeji.mbrowser.工具.mlog
import cn.mujiankeji.mbrowser.数据.配置项.应用配置
import cn.mujiankeji.mbrowser.界面.框架.小窗视图.小窗状态
import cn.mujiankeji.mbrowser.界面.组件.布局.底部窗口布局
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch

/**
 * 下载请求窗口状态
 * 
 * 用于显示下载确认对话框，让用户确认是否下载文件
 * 
 * @param url 下载地址
 * @param userAgent 用户代理
 * @param contentDisposition 内容处置信息
 * @param mimetype 文件MIME类型
 * @param contentLength 文件大小（字节）
 */
class 请求下载窗口状态(
    val url: String,
    val userAgent: String?,
    val contentDisposition: String?,
    val mimetype: String?,
    val contentLength: Long
) : 小窗状态() {

    var coroutine : CoroutineScope? =null
    /**
     * 从URL或contentDisposition中提取文件名
     */
    fun 获取文件名(): String {
        // 尝试从contentDisposition中提取文件名
        contentDisposition?.let { disposition ->
            try {
                // 1. 先尝试RFC 5987格式 (filename*=UTF-8''encoded-value)
                val filenameStarPattern = "filename\\*=(?:UTF-8|utf-8)''([^\"\\s;]*)".toRegex(RegexOption.IGNORE_CASE)
                val matchStar = filenameStarPattern.find(disposition)
                matchStar?.groupValues?.getOrNull(1)?.let { filename ->
                    if (filename.isNotEmpty()) {
                        return java.net.URLDecoder.decode(filename, "UTF-8")
                    }
                }
                
                // 2. 再尝试标准格式 (filename="value")
                val filenamePattern = "filename\\s*=\\s*\"([^\"]*)\"".toRegex()
                val match = filenamePattern.find(disposition)
                match?.groupValues?.getOrNull(1)?.let { filename ->
                    if (filename.isNotEmpty()) {
                        // 尝试URL解码，可能是URL编码的
                        return try {
                            java.net.URLDecoder.decode(filename, "UTF-8")
                        } catch (e: Exception) {
                            filename
                        }
                    }
                }
                
                // 3. 最后尝试无引号格式 (filename=value)
                val filenameNoQuotesPattern = "filename\\s*=\\s*([^\"\\s;]*)".toRegex()
                val matchNoQuotes = filenameNoQuotesPattern.find(disposition)
                matchNoQuotes?.groupValues?.getOrNull(1)?.let { filename ->
                    if (filename.isNotEmpty()) {
                        // 尝试URL解码，可能是URL编码的
                        return try {
                            java.net.URLDecoder.decode(filename, "UTF-8")
                        } catch (e: Exception) {
                            filename
                        }
                    }
                }
            } catch (e: Exception) {
                mlog("解析Content-Disposition失败", e)
            }
        }
        
        // 如果contentDisposition中没有文件名，从URL中提取
        val urlPath = try {
            java.net.URL(url).path
        } catch (e: Exception) {
            ""
        }
        
        if (urlPath.isNotEmpty()) {
            val lastSlashIndex = urlPath.lastIndexOf('/')
            if (lastSlashIndex != -1 && lastSlashIndex < urlPath.length - 1) {
                val filename = urlPath.substring(lastSlashIndex + 1)
                // 尝试URL解码，可能是URL编码的
                return try {
                    java.net.URLDecoder.decode(filename, "UTF-8")
                } catch (e: Exception) {
                    filename
                }
            }
        }
        
        // 如果无法从URL中提取文件名，根据MIME类型生成一个默认文件名
        val extension = when (mimetype) {
            "application/pdf" -> ".pdf"
            "image/jpeg" -> ".jpg"
            "image/png" -> ".png"
            "application/zip" -> ".zip"
            "application/vnd.android.package-archive" -> ".apk"
            "text/plain" -> ".txt"
            "application/msword" -> ".doc"
            "application/vnd.openxmlformats-officedocument.wordprocessingml.document" -> ".docx"
            "application/vnd.ms-excel" -> ".xls"
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" -> ".xlsx"
            else -> ".bin"
        }
        
        return "download_${System.currentTimeMillis()}$extension"
    }
    
    /**
     * 获取格式化的文件大小
     */
    fun 获取格式化文件大小(): String {
        if (contentLength <= 0) return "未知大小"
        
        val units = arrayOf("B", "KB", "MB", "GB", "TB")
        var size = contentLength.toDouble()
        var unitIndex = 0
        
        while (size >= 1024 && unitIndex < units.size - 1) {
            size /= 1024
            unitIndex++
        }
        
        return String.format("%.2f %s", size, units[unitIndex])
    }

    /**
     * 执行下载操作
     */
    fun 下载() {
        val 文件名 = 获取文件名()
        
        mlog("开始下载文件: $文件名, URL: $url")

        coroutine?.launch {
            try {
                应用接口.下载(
                    url = url,
                    文件名 = 文件名,
                    目标路径 = 应用配置.路径_下载 ,
                    userAgent = userAgent
                )
                应用接口.输出提示("开始下载: $文件名")
            } catch (e: Exception) {
                mlog("下载失败", e)
                应用接口.输出提示("下载失败: ${e.message}")
            } finally {
                销毁小窗()
            }
        }
    }

    /**
     * 取消下载
     */
    fun 取消() {
        super.销毁小窗()
    }
}

/**
 * 下载请求窗口实现
 * 
 * @param 状态 下载请求窗口状态
 */
@Composable
fun 下载请求窗口实现(状态: 请求下载窗口状态) {
    状态.coroutine = rememberCoroutineScope()
    DisposableEffect(Unit) {
        onDispose {
            状态.coroutine = null
        }
    }
    val 文件名 = remember { 状态.获取文件名() }
    val 文件大小 = remember { 状态.获取格式化文件大小() }

    底部窗口布局(
        销毁 = { 状态.取消() }
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 20.dp, vertical = 16.dp)
        ) {
            // 标题
            Text(
                text = "下载文件",
                style = MaterialTheme.typography.titleLarge,
                modifier = Modifier.padding(bottom = 16.dp)
            )
            
            // 文件名
            Text(
                text = 文件名,
                style = MaterialTheme.typography.bodyLarge,
                fontWeight = FontWeight.Bold,
                overflow = TextOverflow.Ellipsis,
                modifier = Modifier.padding(bottom = 8.dp)
                    .weight(1f)
            )
            
            // 文件信息
            // 文件大小
            Row(modifier = Modifier.fillMaxWidth()
                .padding(vertical = 5.dp)) {
                Text(
                    text = "大小",
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
                Text(
                    text = 文件大小,
                    style = MaterialTheme.typography.bodyMedium,
                    fontWeight = FontWeight.Medium
                )
            }

            // 文件类型
            Row(modifier = Modifier.fillMaxWidth()
                .padding(vertical = 5.dp)) {
                Text(
                    text = "类型",
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
                Text(
                    text = 状态.mimetype?.substringAfter("/") ?: "未知",
                    style = MaterialTheme.typography.bodyMedium,
                    fontWeight = FontWeight.Medium,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis
                )
            }
            
            // 按钮
            Row(
                modifier = Modifier.fillMaxWidth()
            ) {
                // 取消按钮
                OutlinedButton(
                    onClick = { 状态.取消() },
                    modifier = Modifier.weight(1f)
                ) {
                    Text("取消")
                }
                
                Spacer(modifier = Modifier.width(16.dp))
                
                // 下载按钮
                Button(
                    onClick = { 状态.下载() },
                    modifier = Modifier.weight(1f)
                ) {
                    Text("下载")
                }
            }

            Spacer(Modifier.height(15.dp))
        }
    }
}